<template>
  <div class="wh-full pos-relative">
    <div class="full-left">
      <v-chart :option="mapOption" :autoresize="true" @click="handleClick" />
      <div class="btn" @click="goBack" v-show="isShowBack"></div>
    </div>
    <div class="full-top">
      <div class="top-top">
        <div class="top-item" @click="handlerjump">
          <div class="item-title">重点单位</div>
          <div class="item-num">
            <span class="number">{{ data.cnt1 || 0 }}</span>
            <span class="unit">家</span>
          </div>
        </div>
        <div class="top-item">
          <div class="item-title">累计检查</div>
          <div class="item-num">
            <span class="number">{{ data.checkCnt || 0 }}</span>
            <span class="unit">条</span>
          </div>
        </div>
        <div class="top-item">
          <div class="item-title">隐患上报</div>
          <div class="item-num">
            <span class="number">{{ data.warnCnt || 0 }}</span>
            <span class="unit">条</span>
          </div>
        </div>
        <div class="top-item">
          <div class="item-title">待处置</div>
          <div class="item-num">
            <span class="number">{{ data.warnNoCheckCnt || 0 }}</span>
            <span class="unit">条</span>
          </div>
        </div>
      </div>
      <div class="top-bottom">
        <AutoScroll>
          <template v-slot:content>
            <div
              class="bottom-item"
              v-for="(item, index) in warnDtlListdata"
              :key="index"
            >
              <div class="title">{{ item.typeName }}</div>
              <div class="content" style="width: 570px">
                {{ item.warnName }}
              </div>
              <div class="time">{{ item.createTime }}</div>
              <img
                src="@/assets/images/jumpback.png"
                alt=""
                style="width: 16px; height: 16px"
                @click="handlerdanger(item)"
              />
            </div>
          </template>
        </AutoScroll>
      </div>
    </div>
    <div class="full-right">
      <div
        class="right-item"
        v-for="(item, index) in driveScoredata"
        :key="index"
      >
        <div class="city">{{ item.name }}</div>
        <div class="num">{{ item.data || 0 }}个</div>
        <div class="proportion">{{ item.profit }}%</div>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts" name="EchartsMap">
import { use, registerMap } from "echarts/core";
import AutoScroll from "@/components/Autoscroll/autoscroll.vue";
import VChart from "vue-echarts";
import { CanvasRenderer } from "echarts/renderers";
import { MapChart, ScatterChart, EffectScatterChart } from "echarts/charts";
import {
  TitleComponent,
  TooltipComponent,
  LegendComponent,
  GridComponent,
  VisualMapComponent,
} from "echarts/components";
import {
  getuserPostion,
  getdriveScoreGetZone,
  getdriveScoreGetStreet,
  getdriveScore,
  getareacode,
} from "@/api/chart/chart";
import useUserStore from "@/store/modules/user";
import { ElMessage, ElMessageBox } from "element-plus";
import { useRouter } from "vue-router";
const router = useRouter();

const userStore = useUserStore();

use([
  CanvasRenderer,
  TitleComponent,
  TooltipComponent,
  LegendComponent,
  GridComponent,
  VisualMapComponent,
  MapChart,
  ScatterChart,
  EffectScatterChart,
]);

const mapOption = ref();
const mapList = ref([]); // 记录地图
const isShowBack = computed(() => {
  return mapList.value.length !== 0;
});

const getMapJson = async (mapName) => {
  const url = `http://geo.datav.aliyun.com/areas_v3/bound/${mapName}.json`;
  const mapJson = await fetch(url).then((res) => res.json());
  return mapJson;
};

const setOptions = (mapName, mapData) => {
  return {
    tooltip: {
      show: true,
      backgroundColor: "rgba(9, 24, 48, 0.5)",
      borderColor: "rgba(75, 253, 238, 0.4)",
      textStyle: {
        color: "#CFE3FC",
      },
      formatter: function (params) {
        // 根据需要进行数据处理或格式化操作
        if (params && params.data) {
          const { adcode, name, data, data1, data2, data3 } = params.data;
          if (params.seriesName != "散点") {
            // 返回自定义的tooltip内容
            return `${name}<br>
          <span">单位数量：</span> ${data}<br>
           <span" style="color: #c5dbf4;">绿色单位：</span> <span" style="color: green;">${data1} </span> 家<br>
           <span" style="color: #c5dbf4;">橙色单位：</span> <span" style="color: orange;">${data2} </span>家 <br>
           <span" style="color: #c5dbf4;">红色单位：</span> <span" style="color: red;">${data3}</span> 家<br>
          `;
          } else {
            return `${name}<br>
          <div style="display:flex; align-items: baseline;"><span>地址：</span><span style="display:inline-block;width: 300px;word-wrap: break-word;white-space: normal;">${params.data.streetAddress} </span> </div>
           <span>单位类型：</span> <span>${params.data.streetType} </span> <br>
           <span>单位级别：</span> <span>${params.data.streetLevel} </span> <br>
           <span>行业主管：</span> <span>${params.data.streetIndustry} </span> <br>
           <span>最近检查时间：</span> <span>${params.data.lastCheckDate} </span> <br>
          `;
          }
        }
      },
    },
    // visualMap: {
    //   show: true,
    //   min: 0,
    //   max: 100,
    //   left: "left",
    //   top: "bottom",
    //   text: ["高", "低"], // 文本，默认为数值文本
    //   calculable: true,
    //   seriesIndex: [0],
    //   inRange: {
    //     color: ["#1686ce", "#1a3d64"], // 蓝绿
    //   },
    // },
    geo: {
      map: mapName,
      roam: true,
      select: false,
      // zoom: 1.2,
      layoutCenter: ["38%", "50%"],
      layoutSize: 500,
      // 图形上的文本标签，可用于说明图形的一些数据信息，比如值，名称等。
      selectedMode: "single",
      label: {
        show: true,
      },
      itemStyle: {
        normal: {
          areaColor: "#1c84c7",
          borderColor: "#0a53e9", //线
          shadowColor: "#092f8f", //外发光
          shadowBlur: 20,
        },
        emphasis: {
          areaColor: "#207e8c", //悬浮区背景
        },
      },
      emphasis: {
        itemStyle: {
          areaColor: "#389BB7",
          borderColor: "#389BB7",
          borderWidth: 0,
        },
        label: {
          fontSize: 14,
        },
      },
    },
    series: [
      // 数据
      {
        type: "map",
        map: mapName,
        roam: true,
        geoIndex: 0,
        select: false,
        data: mapData,
        itemStyle: {
          // 正常状态下地图区域的颜色
          normal: {
            areaColor: "#323c48", // 设置地图区域的基本颜色
            borderColor: "#111", // 设置区域边框颜色
            shadowColor: "rgba(0, 0, 0, 0.5)", // 设置阴影颜色
            shadowBlur: 20, // 设置阴影模糊度
          },
          // 鼠标悬停或选中状态下地图区域的颜色
          emphasis: {
            areaColor: "#2B91B7", // 高亮时的地图区域颜色
            borderColor: "#0a539e",
            shadowColor: "rgba(0, 0, 0, 0.5)",
            shadowBlur: 10,
          },
        },
      },
      {
        name: "散点",
        type: "scatter",
        coordinateSystem: "geo",
        data: icondata,
        itemStyle: {
          // 使用回调函数动态设置颜色
          color: function (params) {
            // console.log("params", params);
            if (params.data.streetValue == 1) {
              return "green";
            } else if (params.data.streetValue == 2) {
              return "orange";
            } else if (params.data.streetValue == 3) {
              return "red";
            }
          },
        },
      },
      {
        name: "点",
        type: "scatter",
        coordinateSystem: "geo",
        symbol: "pin", //气泡
        symbolSize: function (val) {
          if (val) {
            return val[2] / 4 + 20;
          }
        },
        label: {
          show: true,
          formatter: function (params) {
            return params.data.data || 0;
          },
          color: "#fff",
          fontSize: 9,
        },
        itemStyle: {
          color: "#F62157", //标志颜色
        },
        zlevel: 6,
        data: mapData,
      },
      {
        name: "Top 5",
        type: "effectScatter",
        coordinateSystem: "geo",
        data: mapData,
        symbolSize: 15,
        showEffectOn: "render",
        rippleEffect: {
          brushType: "stroke",
        },
        label: {
          formatter: "{b}",
          position: "right",
          show: true,
        },
        itemStyle: {
          color: "yellow",
          shadowBlur: 10,
          shadowColor: "yellow",
        },
        zlevel: 1,
      },
    ],
  };
};
let icondata = [];
let Bubbledata = [];
let mapdata = [];
const renderMapEcharts = async (mapName) => {
  const mapJson = await getMapJson(mapName);
  registerMap(mapName, mapJson);
  mapdata = driveScoredata.value.map((item) => {
    return {
      name: item.name,
      value: item.value, // 中心点经纬度
      adcode: item.adcode, // 区域编码
      level: item.level, // 层级
      data: item.data || 0, // 模拟数据
      data1: item.data1 || 0,
      data2: item.data2 || 0,
      data3: item.data3 || 0,
    };
  });
  mapOption.value = setOptions(mapName, mapdata);
};

// 点击下砖
const handleClick = (param) => {
  //   console.log("paramclick", param);
  // 只有点击地图才触发
  if (param.seriesType !== "map") return;
  if (!param.data) {
    return ElMessage.error("没有数据或已经是最下层了");
  }
  const { adcode, level } = param.data;
  const mapName = level === "district" ? adcode : adcode + "_full";
  // 防止最后一个层级被重复点击，返回上一级出错
  if (mapList.value[mapList.value.length - 1] === mapName) {
    return ElMessage.error("没有数据或已经是最下层了");
  }
  mapList.value.push(param.data);
  let func;
  if (level == "district") {
    func = getdriveScoreGetStreet;
  } else {
    func = getdriveScoreGetZone;
  }
  func({
    areaCode: adcode,
  }).then((res) => {
    if (level == "district") {
      driveScoredata.value = [];
      icondata = res.driveScoreStreet;
      renderMapEcharts(mapName);
    } else {
      driveScoredata.value = res.driveScoreZone;
      renderMapEcharts(mapName);
    }
  });
};

// 点击返回上一级地图
const goBack = () => {
  //   console.log("mapList.value", mapList.value);
  const mapName = mapList.value[mapList.value.length - 2]
    ? mapList.value[mapList.value.length - 2].adcode + "_full"
    : `${mapEchartcode.value}_full`;
  let func;
  let obj = {};
  if (mapList.value.length == 2) {
    obj = {
      areaCode: mapList.value[0].adcode,
    };
    func = getdriveScoreGetZone;
  } else {
    obj = {
      type: 1,
    };
    func = getdriveScore;
  }
  func(obj).then((res) => {
    if (mapList.value.length == 2) {
      driveScoredata.value = [];
      driveScoredata.value = res.driveScoreZone;
      icondata = [];
      mapList.value.pop();
      renderMapEcharts(mapName);
    } else {
      driveScoredata.value = res.driveScore;
      mapList.value.pop();
      renderMapEcharts(mapName);
    }
  });
};

let data = ref({});
let driveScoredata = ref([]);
let warnDtlListdata = ref([]);
const accept = (info, driveScore = [], warnDtlList, params) => {
  //   console.log("params", params);
  data.value = info;
  driveScoredata.value = driveScore;
  warnDtlListdata.value = warnDtlList;
  if (params.region.length > 0) {
    switch (userStore.authorityType) {
      case 0:
        if (params.region.length == 1) {
          getareacode(params.cityId).then((res) => {
            renderMapEcharts(`${res.data.code}_full`); // 初始化地图
          });
        }
        if (params.region.length == 2 || params.region.length == 3) {
          getareacode(params.zoneId).then((res) => {
            renderMapEcharts(`${res.data.code}`); // 初始化地图
          });
        }
        break;
      case 1:
        // console.log("zhixing");
        if (params.region.length == 1 || params.region.length == 2) {
          getareacode(params.zoneId).then((res) => {
            renderMapEcharts(`${res.data.code}`); // 初始化地图
          });
        }
        break;

      default:
        break;
    }
  } else {
    if (userStore.authorityType == 2 || userStore.authorityType == 3) {
      getdriveScoreGetStreet({
        areaCode: mapEchartcode.value,
      }).then((res) => {
        driveScoredata.value = [];
        icondata = res.driveScoreStreet;
        // console.log("icondata", icondata);
      });
    }
    if (userStore.authorityType == 2 || userStore.authorityType == 3) {
      renderMapEcharts(`${mapEchartcode.value}`); // 初始化地图
    } else {
      renderMapEcharts(`${mapEchartcode.value}_full`); // 初始化地图
    }
  }
};
/**
 * @description: 获取用户位置
 */
let mapEchartcode = ref("");
const getuserPostiondata = () => {
  getuserPostion({
    type: 1,
  }).then((res) => {
    let { userPostion } = res;
    if (userStore.authorityType == 0) {
      mapEchartcode.value = userPostion.provinceCode;
    } else if (userStore.authorityType == 1) {
      mapEchartcode.value = userPostion.cityCode;
    } else if (userStore.authorityType == 2) {
      mapEchartcode.value = userPostion.zoneCode;
    } else {
      mapEchartcode.value = userPostion.zoneCode;
    }
  });
};
/**
 * @description: 处理跳转
 */
const handlerdanger = (item) => {
  router.push({
    path: "/danger",
    query: {
      indexStrip: true,
      businessId: item.taskId,
      taskDisposalId: item.taskDisposalId,
    },
  });
};

/**
 * @description: 处理跳转
 */
const handlerjump = () => {
  router.push({
    path: "/erp",
  });
};

onMounted(() => {
  // renderMapEcharts("100000_full"); // 初始化绘制中国地图
  getuserPostiondata();
});

defineExpose({ accept });
</script>

<style scoped lang="scss">
.wh-full {
  display: flex;
  position: relative;
  width: 100%;
  height: 100%;
  .full-top {
    position: absolute;
    top: 0px;
    left: 0px;
    width: 100%;
    height: 130px;
    padding: 5px 20px;
    .top-top {
      display: flex;
      justify-content: space-between;
      .top-item {
        display: flex;
        flex-direction: column;
        justify-content: center;
        align-items: center;
        width: 210px;
        height: 95px;
        background: url("@/assets/images/mapback1.png") no-repeat;
        background-size: 100% 100%;
        color: #ffffff;
        font-size: 12px;
        padding-left: 40px;
        .item-title {
          font-size: 14px;
        }
        .item-num {
          font-weight: bold;
          font-size: 20px;
          .number {
            color: #ffffff;
            background: linear-gradient(180deg, #83d0fe 0%, #ffffff 100%);
            -webkit-background-clip: text;
            -webkit-text-fill-color: transparent;
          }
          .unit {
            font-size: 12px;
            color: #a0a5ab !important;
          }
        }
      }
      .top-item:nth-child(2) {
        background: url("@/assets/images/mapback2.png") no-repeat;
        background-size: 100% 100%;
        .item-num {
          .number {
            color: #ffffff;
            background: linear-gradient(180deg, #38b7d2 0%, #ffffff 100%);
            -webkit-background-clip: text;
            -webkit-text-fill-color: transparent;
          }
        }
      }
      .top-item:nth-child(3) {
        background: url("@/assets/images/mapback3.png") no-repeat;
        background-size: 100% 100%;
        .item-num {
          .number {
            color: #ffffff;
            background: linear-gradient(180deg, #f94315 0%, #ffffff 100%);
            -webkit-background-clip: text;
            -webkit-text-fill-color: transparent;
          }
        }
      }
      .top-item:nth-child(4) {
        background: url("@/assets/images/mapback4.png") no-repeat;
        background-size: 100% 100%;
        .item-num {
          .number {
            color: #ffffff;
            background: linear-gradient(180deg, #eaac3a 0%, #ffffff 100%);
            -webkit-background-clip: text;
            -webkit-text-fill-color: transparent;
          }
        }
      }
    }
    .top-bottom {
      cursor: pointer;
      margin: 5px auto 0 auto;
      width: 90%;
      height: 30px;
      background: url("@/assets/images/danderbac.png") no-repeat;
      background-size: 100% 100%;
      .bottom-item {
        display: flex;
        justify-content: space-between;
        align-items: center;
        padding: 0 35px;
        font-size: 12px;
        color: #ffffff;
        height: 30px;
        .title {
          font-size: 15px;
          font-weight: 700;
          background: linear-gradient(180deg, #d09696 0%, #ffffff 100%);
          -webkit-background-clip: text;
          -webkit-text-fill-color: transparent;
        }
      }
    }
  }
  .full-left {
    position: relative;
    width: 100%;
    height: 100%;
    .btn {
      position: absolute;
      bottom: 20px;
      left: 50px;
      width: 80px;
      height: 30px;
      background: url("@/assets/images/mapback.png") no-repeat;
    }
  }
  .full-right {
    position: absolute;
    top: 0;
    right: 30px;
    width: 25%;
    height: 100%;
    margin-top: 200px;
    /* background-color: red; */
    overflow-y: scroll;
    height: 35vh;
    .right-item {
      display: flex;
      justify-content: space-evenly;
      color: #ffffff;
      font-size: 12px;
      padding: 6px 0px 6px 10px;
      .num {
        width: 80px;
        color: #51a6dd;
      }
      .city {
        width: 80px;
      }
      .proportion {
        width: 40px;
      }
    }
    .right-item:nth-child(odd) {
      background-color: rgba(24, 49, 71, 0.8);
    }
    .right-item:nth-child(even) {
      background-color: rgba(15, 32, 50, 0.4);
    }
  }
  .full-right::-webkit-scrollbar {
    display: none;
  }
}
</style>
